package filter;

import Pojo.User;
import Utils.BaseMessage;
import com.alibaba.fastjson.JSON;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "isAdminFilter", urlPatterns = {
        "/api/Site/isAdmin/*",
        "/api/User/isAdmin/*",
        "/api/CreditCard/isAdmin/*",
        "/api/Bank/isAdmin/*"
})
public class isAdminFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("userMsg");
        if (user == null) {
            response.getWriter().print(JSON.toJSONString(new BaseMessage(1, "您暂未登录,请登陆后操作", null)));
        }
        if (user.getUserRole() == 2) {
            chain.doFilter(req, resp);
            return;
        }
        response.getWriter().print(JSON.toJSONString(new BaseMessage(1, "您不是管理员请不要访问此页面", null)));
        return;

    }

    public void init(FilterConfig config) throws ServletException {

    }

}
